% Solve for the Ramsey problem with a flat tax

temp.coef  = pr.Om.^(-1/(pr.gam+pr.sig)).*w.^((1+pr.sig)/(pr.gam+pr.sig));
r_flat.tau = fzero(@(x) sum(pai.*(1-x).^((1-pr.gam)/(pr.gam+pr.sig)).*temp.coef) ...
                       -sum(pai.*(1-x).^((1+pr.sig)/(pr.gam+pr.sig)).*temp.coef)-G,G);

%% Allocation
r_flat.c       = (1-r_flat.tau).^((1+pr.sig)/(pr.gam+pr.sig)).*temp.coef;
r_flat.y       = (1-r_flat.tau).^((1-pr.gam)/(pr.gam+pr.sig)).*temp.coef;
r_flat.output  = sum(pai.*r_flat.y);
r_flat.welfare = sum(pw.*pai.*Utility(r_flat.c,r_flat.y,w,pr));
r_flat.MTR     = 1-pr.Om./r_flat.c.^(-pr.gam).*w.^-(1+pr.sig).*r_flat.y.^pr.sig;
r_flat.ATR     = (r_flat.y-r_flat.c)./r_flat.y;
r_flat.WelfareGain = 100*fzero(@(x) sum(pw.*pai.*Utility((1+x).*baseline.c,baseline.y,w,pr))-r_flat.welfare,.5);
r_flat.OutputLoss  = 100*(r_flat.output/baseline.output-1);
r_flat.EfAveMTR = sum(pai.*r_flat.MTR.*r_flat.y/r_flat.output);
[temp.y,temp.i] = min(r_flat.y);
temp.c          = r_flat.c(temp.i);
r_flat.Tr2Y     = (temp.c-temp.y)./r_flat.output;
r_flat.TrG2Y    = (temp.c-temp.y+G)./r_flat.output;

save ./variables/r_flat r_flat
clear temp